package com.blog.serlvet;

import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.User;
import com.blog.dao.BlogDao;
import com.blog.util.LoginUtil;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class PublishBlogServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = LoginUtil.checkApiLogin(session, resp);
        if (user == null) {
            return;
        }

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        String content = req.getParameter("content");
        if (content == null
                || content.length() < 1
                || content.length() > 500) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "微博内容不正确", null)));
            return;
        }

        BlogDao blogDao = new BlogDao();
        try {
            blogDao.publishBlog(content, user.getId());
            writer.println(JSONObject.toJSONString(new BaseResponse(200, "微博发送成功", null)));
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(500);
        }
    }
}
